package com.zhenyi.xiaohuoche.index;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hashids.Hashids;
import org.joda.time.DateTime;

import com.aliyuncs.exceptions.ClientException;
import com.cjw.model.DBMap;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.sdk.api.PaymentApi;
import com.jfinal.weixin.sdk.api.PaymentApi.TradeType;
import com.jfinal.weixin.sdk.kit.IpKit;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.utils.AuthUtils;
import com.utils.PathUtils;
import com.utils.interceptor.TestInterceptor;
import com.xhc.common.model.XhcEnroll;
import com.xhc.common.model.XhcGroup;
import com.xhc.common.model.XhcOrder;
import com.xhc.common.model.XhcTicket;
import com.xhc.common.model.XhcUserTicket;
import com.xhc.common.model.XhcWechat;
import com.zhenyi.core.AES;
import com.zhenyi.xhc.core.TicketUtils;
import com.zhenyi.xhc.core.XHCController;
import com.zhenyi.xiaohuche.utils.SMSUtils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;

public class TicketController extends XHCController {

	@Override
	public void index() {
		genQRCode("fcjuk");
		renderSuccess();
	}

	public void test() {
		// Setting setting = new Setting("xhc.setting");
		setting.get("abc");
		String key = "title1";
		String group = "ticketSetting";
		String defaultValue = "defaultValue";
		String value = setting.getStr(key, group, defaultValue);
		renderText(value);
	}

	/**
	 * 当前日期票务信息
	 */
	@Clear
	@Override
	public void list() {
		String date = getPara("date", DateUtil.today());
		// Date start = getOpenTime(date);
		// Date end = getCloseTime(date);
		// end = new DateTime(end).plusHours(-1).toDate();
		String start = date + " 00:00";
		String end = date + " 23:59";
		SqlPara sqlPara = xhcDb.getSqlPara("XHCTK", start, end);
		List<XhcTicket> items = XhcTicket.dao.find(sqlPara);

		Date now = new Date();
		for (XhcTicket xhcTicket : items) {
			xhcTicket.setDefaultInfo();
			// if (xhcTicket.getLimit() == null) {
			// xhcTicket.setLimit(setting.getInt("limit", "ticketSetting",
			// 100));
			// }
			if (xhcTicket.getPrice1() == null) {
				Integer value = setting.getInt("adultPrice", "ticketSetting", 60);
				xhcTicket.setPrice1(new BigDecimal(value));
			}
			int delay = PropKit.getInt("XHC_TICKET_PAY_DELAY", 30);
			boolean enable = now.getTime() <= new DateTime(xhcTicket.getTime()).plusMinutes(delay).toDate().getTime();
			xhcTicket.put("enable", enable);

			// if (xhcTicket.getPrice2() == null) {
			// Integer value = setting.getInt("childrenPrice", "ticketSetting",
			// 30);
			// xhcTicket.setPrice2(new BigDecimal(value));
			// }
			// if (xhcTicket.getPrice3() == null) {
			// Integer value = setting.getInt("packagePrice", "ticketSetting",
			// 80);
			// xhcTicket.setPrice3(new BigDecimal(value));
			// }
			// xhcTicket.setTips("特殊票文字");
		}
		renderResult(items);
	}

	/**
	 * 返回票信息
	 */
	public void info() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderFailure("id is null");
			return;
		}
		XhcTicket info = XhcTicket.dao.findById(id);
		renderResult(info);
	}

	/**
	 * 返回默认票价,默认票限量
	 */
	@Clear
	// @Before(CacheInterceptor.class)
	// @CacheName("1hour")
	public void init() {
		// String settingPath = PathUtils.getFile("xhc", "xhc.setting");
		// Setting setting = new Setting(settingPath);
		int adultPrice = setting.getInt("adultPrice", "setting", 60);

		/**
		 * 注释了
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 */
		// setting.set("adultPrice", "setting", adultPrice + 1);
		/**
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 */

		String notice = new FileReader(PathUtils.getFile("xhc", "notice.txt")).readString();
		String agreement = new FileReader(PathUtils.getFile("xhc", "agreement.txt")).readString();
		// String notification = new FileReader(PathUtils.getFile("xhc",
		// "notification.txt")).readString();

		String notification = new FileReader(PathUtils.getFile("data", "xhc", "notification.txt")).readString();
		String businessTime = new FileReader(PathUtils.getFile("data", "xhc", "businessTime.txt")).readString();
		businessTime = businessTime.replace("</br>", "\n");

		String openTime = PropKit.get("XHC_OPEN_TIME", "10:00");// new
		// FileReader(PathUtils.getFile("xhc",
		// "openTime.txt")).readString();
		String closeTime = PropKit.get("XHC_CLOSE_TIME", "20:30");// new
		// FileReader(PathUtils.getFile("xhc",
		// "closeTime.txt")).readString();
		DBMap map = new DBMap();
		map.put("notice", notice);
		map.put("agreement", agreement);
		map.put("notification", notification);
		map.put("businessTime", businessTime);
		map.put("openTime", openTime);
		map.put("closeTime", closeTime);
		map.put("images", new FileReader(PathUtils.getFile("xhc", "images.txt")).readString());
		renderResult(map);
	}

	// public void gen() {
	// new TicketUtils().genTicket();
	// renderSuccess();
	// }

	@Before(Tx.class)
	public void pay() {
		String code = getPara("code");
		String mobile = getPara("mobile");
		if (!verifyCode(code, mobile)) {
			renderMsg("验证码错误");
			return;
		}
		Integer price1Count = getParaToInt("price1Count", 0);
		Integer price2Count = getParaToInt("price2Count", 0);
		Integer price3Count = getParaToInt("price3Count", 0);
		Integer price4Count = getParaToInt("price4Count", 0);
		Integer price5Count = getParaToInt("price5Count", 0);

		Long ticketId = getParaToLong("ticketId");
		if (ticketId == null) {
			renderFailure("ticket id error");
			return;
		}

		String name = getPara("name", "未填写");
		String openId = getOpenId();
		if (StrKit.isBlank(openId)) {
			renderFailure("openId null");
			return;
		}

		XhcTicket ticket = XhcTicket.dao.findById(ticketId);
		BigDecimal totalPrice = new BigDecimal(0);
		totalPrice = totalPrice.add(ticket.getPrice1().multiply(new BigDecimal(price1Count)));
		totalPrice = totalPrice.add(ticket.getPrice2().multiply(new BigDecimal(price2Count)));
		totalPrice = totalPrice.add(ticket.getPrice3().multiply(new BigDecimal(price3Count)));
		totalPrice = totalPrice.add(ticket.getPrice4().multiply(new BigDecimal(price4Count)));
		totalPrice = totalPrice.add(ticket.getPrice5().multiply(new BigDecimal(price5Count)));
		totalPrice = totalPrice.multiply(new BigDecimal(100));
		String total = totalPrice.intValue() + "";
		if ("0".equals(total)) {
			renderMsg("购买金额不能为0");
			return;
		}
		Date time = ticket.getTime();
		XhcOrder order = new XhcOrder();
		order.setAddTime();
		String ip = IpKit.getRealIpV2(getRequest());
		order.setStatus(0);
		order.setPaidIp(ip);
		// order.setCardId(cardId);
		order.setOpenid(openId);
		order.setAddTime();
		order.setTotalFee(total);
		order.setPrice(Integer.parseInt(total));
		order.setAppId(APP_ID);
		order.setMchId(PARTNER);
		order.setRaw(JsonKit.toJson(ticket));
		order.setName(name);
		order.setMobile(mobile);
		// order.setatta
		order.setAttach("ticket");
		order.save();
		order.setOutTradeNo(hashids.encode(order.getId()));
		// order.setNo(hashids.encode(order.getId()));
		Long orderId = order.getId();
		XhcWechat wechat = XhcWechat.dao.findByOpenId(openId);
		Long wechatId = wechat.getId();
		for (int count = 0; count < price1Count; count++) {
			saveTicket(ticket, orderId, wechatId, time, 1, name, mobile);
		}
		for (int count = 0; count < price2Count; count++) {
			saveTicket(ticket, orderId, wechatId, time, 2, name, mobile);
		}
		for (int count = 0; count < price3Count; count++) {
			saveTicket(ticket, orderId, wechatId, time, 3, name, mobile);
		}
		for (int count = 0; count < price4Count; count++) {
			saveTicket(ticket, orderId, wechatId, time, 4, name, mobile);
		}
		for (int count = 0; count < price5Count; count++) {
			saveTicket(ticket, orderId, wechatId, time, 5, name, mobile);
		}
		String prepayId = renderPay(order.getOutTradeNo(), "小火车", total, openId, order.getAttach());
		order.setPrepayId(prepayId);
		order.update();
	}

	public static void main(String[] args) {
		// String nonce_str = System.currentTimeMillis() / 1000 + "";
		String nonce_str = RandomUtil.randomString(32);
		String tradeNo = "orderNo" + RandomUtil.randomString(8);

		String total_fee = "1";

		String appid = "wxb0d1949acd86ac4d";
		String mch_id = "1509634941";
		String key = "isrdmfgsDihlskjghsrelFHGHnkjvghn";
		String openId = "opaGZ5TapmsQyQEVJVAu1YVIjUqQ";

		// String appid = "wx6d47db34d18f5e3a";
		// String mch_id = "1494469742";
		// String key = "zhenyikejizhenyikejizhenyikejizy";
		// String openId = "oAngF0aL70QtHPj7-i7WvpLWq8Ga";

		Map<String, String> params = new HashMap<String, String>();
		params.put("appid", appid);
		params.put("mch_id", mch_id);
		params.put("nonce_str", nonce_str);
		params.put("body", "测试购买");
		params.put("out_trade_no", tradeNo);
		params.put("total_fee", total_fee);
		String ip = "127.0.0.1";
		params.put("spbill_create_ip", ip);
		params.put("trade_type", TradeType.JSAPI.name());
		params.put("notify_url", "https://release.zhen-yee.com/xhc/bill/billPush");
		params.put("openid", openId);
		// params.put("sign_type", "MD5");
		// System.out.println("attach:" + attach);
		// if (StrKit.notBlank(attach)) {
		// params.put("attach", attach);
		// }
		// System.out.println(JsonKit.toJson(params));
		String sign = PaymentKit.createSign(params, key);
		params.put("sign", sign);
		System.out.println(JsonKit.toJson(params));
		String xmlResult = PaymentApi.pushOrder(params);
		Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
		System.out.println(result);
	}

	public void testPush() {
		Map<String, String> params = new HashMap<String, String>();
		params.put("appid", "wxd930ea5d5a258f4f");
		params.put("mch_id", "10000100");
		params.put("body", "test");
		params.put("device_info", "1000");
		params.put("nonce_str", "ibuaiVcKdpRxkhJA");
		String sign = PaymentKit.createSign(params, PARTNER_KEY);
		System.out.println(sign);
	}

	private boolean saveTicket(XhcTicket ticket, Long orderId, Long wechatId, Date time, int type, String name,
			String mobile) {
		Long ticketId = ticket.getId();
		XhcUserTicket userTicket = new XhcUserTicket();
		userTicket.setTicketId(ticketId);
		userTicket.setOrderId(orderId);
		userTicket.setWechatId(wechatId);
		userTicket.setTime(time);
		userTicket.setAddTime();
		userTicket.setStatus(0);
		userTicket.setName(name);
		userTicket.setMobile(mobile);
		userTicket.setType(type);
		userTicket.setTitle(ticket.getStr("title" + type));
		BigDecimal paid = ticket.getTicketPrice(type);
		paid = paid.multiply(new BigDecimal(100));
		userTicket.setPaid(paid);
		userTicket.save();
		Long id = userTicket.getId();
		String code = piaoHashids.encode(id);
		String url = QRCODE_VERIFY + code;
		genQRCode(code, url);
		String qrcode = "http://qr.liantu.com/api.php?text=" + code;// QRCODE_HOST
																	// + code +
																	// ".png";
		userTicket.setQrcode(qrcode);
		return userTicket.update();
	}

	// public void codes() {
	// List<XhcUserTicket> items = XhcUserTicket.dao.findAll();
	// for (XhcUserTicket userTicket : items) {
	// Long id = userTicket.getId();
	// Hashids hashids = new Hashids("piao", 8);
	// String code = hashids.encode(id);
	// // String url = HOST + code;
	// genQRCode(code);
	// String qrcodeHost = setting.getStr("qrcodeHost", "ticketSetting", "");
	// String qrcode = qrcodeHost + code + ".png";
	// userTicket.setQrcode(qrcode);
	// userTicket.update();
	// }
	// renderSuccess();
	// }

	/**
	 * 退票
	 */
	@Before(Tx.class)
	public void refund() {
		Long id = getParaToLong("id");
		orderUtils.refundTicket(this, id);
	}

	public void orders() {
		tickets();
	}

	public void tickets() {
		XhcWechat wechat = getWechat();
		if (wechat == null) {
			renderFailure();
			return;
		}
		SqlPara sqlPara = xhcDb.getSqlPara("XHCTickets", wechat.getId());
		List<Record> items = xhcDb.find(sqlPara);
		renderResult(items);
	}

	/**
	 * 
	 */
	@Before(Tx.class)
	public void verify() {
		String code = getPara(0);
		Hashids hashids = new Hashids("piao", 8);
		Long id = hashids.decode(code)[0];
		XhcUserTicket userTicket = XhcUserTicket.dao.findById(id);
		if (userTicket.getIsUsed() != null && userTicket.getIsUsed().equals(1)) {
			renderFailure("ticket used");
			return;
		}
		userTicket.setIsUsed(1);
		userTicket.setUseTime(new Date());
		// userTicket.setStatus(1);
		boolean flag = userTicket.update();
		if (flag) {
			XhcEnroll enroll = new XhcEnroll();
			enroll.setAddTime();
			enroll.setWechatId(getWechat().getId());
			enroll.setTicketId(userTicket.getTicketId());
			flag = enroll.save();
		}
		renderFlag(flag);
	}

	/**
	 * 购票协议
	 */
	public void agreement() {
		FileReader fileReader = new FileReader("xhc/agreement.txt");
		String result = fileReader.readString();
		renderResult(result);
	}

	/**
	 * 购票协议
	 */
	public void notice() {
		FileReader fileReader = new FileReader("xhc/notice.txt");
		String result = fileReader.readString();
		renderResult(result);
	}

	@Clear
	public void userInfo() {
		String iv = getPara("iv");
		String code = getPara("code");
		Map<String, Object> info = getSessionKey(APP_ID, APP_SECRET, code);
		String session_key = (String) info.get("session_key");
		String openId = (String) info.get("openid");
		if (!StrKit.notBlank(session_key, openId)) {
			LogKit.error("login blank " + session_key + " - " + openId);
			renderFailure("login error");
			return;
		}
		String encryptedData = getPara("encryptedData");
		String json = AES.de(encryptedData, session_key, iv);
		JSONObject userInfo = new JSONObject(json);
		String nickName = userInfo.getStr("nickName");
		Integer gender = userInfo.getInt("gender");
		String language = userInfo.getStr("language");
		String city = userInfo.getStr("city");
		String province = userInfo.getStr("province");
		String country = userInfo.getStr("country");
		String avatarUrl = userInfo.getStr("avatarUrl");
		String unionid = userInfo.getStr("unionId");
		JSONObject watermark = userInfo.getJSONObject("watermark");
		String appid = watermark.getStr("appid");
		XhcWechat wechat = XhcWechat.dao.findByOpenId(openId);
		if (wechat == null || wechat.getOpenId() == null) {
			wechat = new XhcWechat();
			wechat.setOpenId(openId);
			wechat.setAddTime();
			wechat.save();
		}
		if (StrKit.notBlank(appid)) {
			wechat.setAppid(appid);
		}
		wechat.setSessionKey(session_key);
		if (StrKit.notBlank(unionid)) {
			wechat.setUnionid(unionid);
		}
		if (StrKit.notBlank(nickName)) {
			wechat.setNickName(nickName);
		}
		if (gender != null) {
			wechat.setGender(gender);
		}
		if (StrKit.notBlank(language)) {
			wechat.setLanguage(language);
		}
		if (StrKit.notBlank(city)) {
			wechat.setCity(city);
		}
		if (StrKit.notBlank(province)) {
			wechat.setProvince(province);
		}
		if (StrKit.notBlank(country)) {
			wechat.setCountry(country);
		}
		if (StrKit.notBlank(avatarUrl)) {
			wechat.setAvatarUrl(avatarUrl);
		}
		wechat.setLastLogin(new Date());
		wechat.update();
		// renderResult(openId);
		String token = AuthUtils.login(wechat.getOpenId());
		DBMap map = new DBMap();
		map.put("openId", openId);
		map.put("token", token);
		renderResult(map);
	}

	public void code() {
		String mobile = getPara("mobile");
		if (StrKit.isBlank(mobile)) {
			renderMsg("电话号码不能未空");
			return;
		}
		if (SMSUtils.checkInterval(mobile)) {
			renderMsg("验证码已发送");
			return;
		}
		try {
			SMSUtils.send(mobile);
		} catch (ClientException e) {
			e.printStackTrace();
		}
		renderSuccess();
	}

	protected boolean verifyCode(String code, String mobile) {
		if (StrKit.isBlank(mobile)) {
			return false;
		}
		if (SMSUtils.verify(mobile, code)) {
			return true;
		}
		// if ("709394".equals(code)) {
		// return true;
		// }
		return false;
	}

	/**
	 * 购买团体票
	 */
	@Override
	@Before(Tx.class)
	public void submit() {
		String name = getPara("name");
		String mobile = getPara("mobile");
		String code = getPara("code");
		if (!verifyCode(code, mobile)) {
			renderMsg("验证码错误");
			return;
		}
		XhcGroup group = new XhcGroup();
		group.setName(name);
		group.setMobile(mobile);
		group.setAddTime();
		group.setWechatId(getWechat().getId());
		boolean flag = group.save();
		renderFlag(flag);
	}

	@Before(TestInterceptor.class)
	public void genticket() {
		new TicketUtils().genTicket();
		renderSuccess();
	}
}
